package net.tv90.auth.controller;

import cn.hutool.system.UserInfo;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.constraints.NotEmpty;
import net.tv90.auth.aop.annotation.AccessLimit;
import net.tv90.auth.aop.annotation.NeedVerify;
import net.tv90.auth.exception.AuthException;
import net.tv90.auth.model.dto.UserLoginByEmailDTO;
import net.tv90.auth.model.dto.UserLoginByUsernameDTO;
import net.tv90.auth.model.vo.UserInfoVO;
import net.tv90.auth.model.vo.UserLoginVO;
import net.tv90.auth.service.LoginService;
import net.tv90.auth.utils.web.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@RestController
@CrossOrigin
@Validated
@RequestMapping("/login")
public class LoginController {

    @Autowired
    LoginService loginService;

    @AccessLimit(seconds = 20, maxCount = 5)
    @PostMapping("/email")
    public Result loginByEmail(@Validated @RequestBody UserLoginByEmailDTO dto, HttpServletRequest request) {
        try {
            return Result.success(loginService.loginByEmail(dto, request));
        } catch (AuthException e) {
            return Result.failed(e.getMessage());
        }
    }

    @AccessLimit(seconds = 20, maxCount = 5)
    @PostMapping("/username")
    public Result loginByUserName(@Validated @RequestBody UserLoginByUsernameDTO dto, HttpServletRequest request) {
        try {
            return Result.success(loginService.loginByUsername(dto, request));
        } catch (AuthException e) {
            return Result.failed(e.getMessage());
        }
    }

    @NeedVerify
    @PostMapping("/out")
    public Result logout(@NotEmpty String username) {
        loginService.logout(username);
        return Result.success("登出成功");
    }

    @NeedVerify
    @GetMapping("/vo")
    public Result getLoginVO(@NotEmpty String username) {
        UserInfoVO userInfoVO = loginService.getUserInfo(username);
        if(userInfoVO != null) {
            return Result.success(userInfoVO);
        }
        return Result.failed("用户未登录");
    }

}
